const WIDTH = 260
const HEIGHT = 160
const tpl1 = document.createElement('canvas')
tpl1.setAttribute('id', 'watermark')
tpl1.setAttribute('width', `${WIDTH}px`)
tpl1.setAttribute('height', `${HEIGHT}px`)
tpl1.setAttribute('style', 'display: none;')

const tpl2 = document.createElement('canvas')
tpl2.setAttribute('id', 'repeat-watermark')

class Watermark {
  opt = {
    docWidth: document.documentElement.clientWidth,
    docHeight: document.documentElement.clientHeight,
    fontSize: '20px',
    fontColor: '#000000',
    rotateAngle: -20 * Math.PI  / 180,
    x: 0,
    y: 80,
    watermark: ''
  }

  constructor (container, options = {}) {
    Object.assign(this.opt, options)
    this.opt.x = 0
    this.opt.y = HEIGHT - parseInt(this.opt.fontSize)
    console.log(this.opt)
    this.render(container)
    this.draw(this.opt.docWidth, this.opt.docHeight)
  }

  render (dom) {
    if (document.querySelector('#watermark') && document.querySelector('#repeat-watermark')) {
      return
    }
    dom.appendChild(tpl1)
    dom.appendChild(tpl2)
  }

  draw (docWidth, docHeight) {
    const cw = document.querySelector('#watermark')
    const crw = document.querySelector('#repeat-watermark')

    crw.width = docWidth
    crw.height = docHeight

    const ctx = cw.getContext('2d')
    // 清除小画布
    ctx.clearRect(0, 0, WIDTH, HEIGHT)
    // 设置字体样式
    ctx.font = this.opt.fontSize + ' Arial'
    ctx.fillStyle = this.opt.fontColor
    // 文字倾斜角度
    ctx.rotate(this.opt.rotateAngle)
    // 设置字体内容
    ctx.fillText(this.opt.watermark, this.opt.x, this.opt.y)
    // 坐标系还原
    ctx.rotate(-this.opt.rotateAngle)

    // 重复画图
    const ctxr = crw.getContext('2d')
    ctxr.clearRect(0 , 0, crw.width, crw.height)
    // 平铺ctx
    const pattern = ctxr.createPattern(cw, 'repeat')
    ctxr.fillStyle = pattern
    ctxr.fillRect(0 , 0, crw.width, crw.height)
  }
}

export default Watermark
